//
//  AddLivingPerson_ViewController.m
//  MZSystem
//
//  Created by 智障 on 2018/11/5.
//  Copyright © 2018 zerod. All rights reserved.
//

#import "AddLivingPerson_ViewController.h"

#import "NameAndTrueNameModel.h"

#import "AddPerson_Search_CollectionViewCell.h"
#import "AddPerson_Choose_CollectionViewCell.h"
#import "AddPerson_Kong_CollectionViewCell.h"
#import "AddPerson_Result_CollectionViewCell.h"

@interface AddLivingPerson_ViewController ()<UICollectionViewDataSource, UICollectionViewDelegate,UITextFieldDelegate>
@property (nonatomic, strong) UICollectionView           *collectionView;
@property (nonatomic ,strong) NSMutableArray              *chooseArray,*dataArray;

@property (nonatomic ,strong) Base_CenterNavView         *navView;
@property (nonatomic ,copy)   NSString                   *keywords;
@end

@implementation AddLivingPerson_ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.keywords = @"";
    [self.view addSubview:self.navView];
    [self.view addSubview:self.collectionView];
    [self requsetData];
}
- (NSMutableArray *)chooseArray{
    if (!_chooseArray) {
        _chooseArray = [NSMutableArray new];
        NSArray *baseAry ;
        switch (self.tag) {
            case 1:{
                baseAry = [self.model.streamUsers componentsSeparatedByString:@","];
                if (self.model.streamUsers.length == 0) {
                    baseAry = @[];
                }
            }
                break;
            case 2:{
                baseAry = [self.model.reporters componentsSeparatedByString:@","];
                if (self.model.reporters.length == 0) {
                    baseAry = @[];
                }
            }
                break;
            case 3:{
                baseAry = [self.model.directors componentsSeparatedByString:@","];
                if (self.model.directors.length == 0) {
                    baseAry = @[];
                }
            }
                break;
            case 4:{
                baseAry = [self.model.editors componentsSeparatedByString:@","];
                if (self.model.editors.length == 0) {
                    baseAry = @[];
                }
            }
                break;
                
            default:
                break;
        }
        _chooseArray = [baseAry mutableCopy];
    }
    return _chooseArray;
}
#pragma MARK: UICollectionView 代理
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return 3;
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    if (section == 0) {
        return self.chooseArray.count == 0 ? 1 : self.chooseArray.count;
    }
    if (section == 1) {
        return 1;
    }
    if (section == 2) {
        return self.dataArray.count == 0 ? 1 : self.dataArray.count;
    }
    return 0;
}

-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        AddPerson_Choose_CollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"Choose_Cell" forIndexPath:indexPath];
        if (self.chooseArray.count == 0) {
            cell.nameLabel.hidden = YES;
            cell.deleteButton.hidden = YES;
            cell.tipLabel.hidden = NO;
        }else{
            cell.name = self.chooseArray[indexPath.row];
            cell.nameLabel.hidden = NO;
            cell.deleteButton.hidden = NO;
            if (indexPath.row == 0) {
                cell.tipLabel.hidden = NO;
            }else{
                cell.tipLabel.hidden = YES;
            }
        }
        cell.deleteClick = ^{
            [self.chooseArray removeObjectAtIndex:indexPath.row];
            [collectionView reloadData];
        };
        return cell;
    }
    if (indexPath.section == 1) {
        AddPerson_Search_CollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"Search_Cell" forIndexPath:indexPath];
        cell.TFChange = ^(NSString * _Nonnull text) {
            self.keywords = text;
            [self requsetData];
        };
        return cell;
    }
    if (indexPath.section == 2) {
        if (self.dataArray.count == 0) {
            AddPerson_Kong_CollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"Kong_Cell" forIndexPath:indexPath];
            return cell;
        }else{
            AddPerson_Result_CollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"Result_Cell" forIndexPath:indexPath];
            NameAndTrueNameModel *model = self.dataArray[indexPath.row];
            cell.name = model.username;
            return cell;
        }
        
    }
    return nil;
}

- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath{
    UICollectionReusableView *reusableview = nil;
    return reusableview;
}
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        return CGSizeMake(ScrW, 40.f);
    }
    if (indexPath.section == 1) {
        return CGSizeMake(ScrW, 110.f);
    }
    if (indexPath.section == 2) {
        if (self.dataArray.count == 0) {
            return CGSizeMake(ScrW, 180.f);
        }else{
            NameAndTrueNameModel *model = self.dataArray[indexPath.row];
            float w = [self forWidthFromFont:FontSize14 withHeight:25.f withString:[NSString stringWithFormat:@"%@",model.username]];
            return CGSizeMake(w + 20.f, 25.f);
        }
    }
    return CGSizeZero;
}
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section{
    if (section == 2) {
        return 15.f;
    }
    return 0;
}
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section{
    if (section == 2) {
        return 8.f;
    }
    return 0;
}
- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section{
    if (section == 2) {
        return UIEdgeInsetsMake(5, 15, 5,15);
    }
    return UIEdgeInsetsMake(0, 0, 0, 0);
}
/** 头部区高度 */
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section{
    return CGSizeZero;
}
/** 尾区高度 */
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForFooterInSection:(NSInteger)section{
    return CGSizeZero;
}
//设置分区背景颜色
- (UIColor *)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout colorForSectionAtIndex:(NSInteger)section{
    return [UIColor whiteColor];
}
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 2) {
        if (self.dataArray.count == 0) {
            return;
        }
        NameAndTrueNameModel *model = self.dataArray[indexPath.row];
        if (![self.chooseArray containsObject:model.username]) {
            [self.chooseArray addObject:model.username];
//            [UIView performWithoutAnimation:^{
                [self.collectionView reloadSections:[NSIndexSet indexSetWithIndex:0]];
//            }];
        }
    }
}
- (UICollectionView *)collectionView {
    if (!_collectionView) {
        UICollectionViewFlowLayout *layout= [[UICollectionViewFlowLayout alloc]init];
        _collectionView = [[UICollectionView alloc]initWithFrame:CGRectMake(0, SafeAreaTopHeight, ScrW, ScrH - SafeAreaTopHeight -SafeAreaBottomHeight ) collectionViewLayout:layout];
        _collectionView.backgroundColor = [UIColor whiteColor];
        _collectionView.delegate = self;
        _collectionView.dataSource = self;
        _collectionView.showsVerticalScrollIndicator = NO;
        //注册cell
        [_collectionView registerNib:[UINib nibWithNibName:@"AddPerson_Choose_CollectionViewCell" bundle:nil] forCellWithReuseIdentifier:@"Choose_Cell"];
        [_collectionView registerNib:[UINib nibWithNibName:@"AddPerson_Search_CollectionViewCell" bundle:nil] forCellWithReuseIdentifier:@"Search_Cell"];
        [_collectionView registerNib:[UINib nibWithNibName:@"AddPerson_Result_CollectionViewCell" bundle:nil] forCellWithReuseIdentifier:@"Result_Cell"];
        [_collectionView registerNib:[UINib nibWithNibName:@"AddPerson_Kong_CollectionViewCell" bundle:nil] forCellWithReuseIdentifier:@"Kong_Cell"];
        
    }
    return _collectionView;
}
- (Base_CenterNavView *)navView{
    if (!_navView) {
        _navView = [Base_loadXibView loadFromXib:@"Base_CenterNavView" withCls:[Base_CenterNavView class]];
        [_navView setFrame:CGRectMake(0, 0, SCREEN_WIDTH, SafeAreaTopHeight)];
        
        switch (self.tag) {
            case 1:{_navView.navTitle.text = @"添加直播员";}break;
            case 2:{_navView.navTitle.text = @"添加记者";}break;
            case 3:{_navView.navTitle.text = @"添加导播";}break;
            case 4:{_navView.navTitle.text = @"添加编辑";}break;
            default:
                break;
        }
        _navView.rightbutton.hidden = NO;
        [_navView.rightbutton setTitle:@"保存" forState:UIControlStateNormal];
        WS(weakSelf)
        _navView.clickBack = ^{
            [weakSelf.navigationController popViewControllerAnimated:YES];
        };
        _navView.clickRightBtn = ^{
            [weakSelf saveCurrentName];
        };
    }
    return _navView;
}
- (void)saveCurrentName{
    switch (self.tag) {
        case 1:{
            self.model.streamUsers = [self.chooseArray componentsJoinedByString:@","];
        }
            break;
        case 2:{
            self.model.reporters = [self.chooseArray componentsJoinedByString:@","];
        }
            break;
        case 3:{
            self.model.directors = [self.chooseArray componentsJoinedByString:@","];
        }
            break;
        case 4:{

            self.model.editors = [self.chooseArray componentsJoinedByString:@","];
        }
            break;
            
        default:
            break;
    }
    [self.navigationController popViewControllerAnimated:YES];
}
- (void)requsetData{
//    if (self.keywords.length == 0) {
//        return;
//    }
    NSString*url=[NSString stringWithFormat:@"%@/api/live/searchUser?username=%@",URL_HOST,self.keywords];
    [SendRequest getWithURL:url params:nil withCookie:YES success:^(id response) {
        int code = [response[@"code"] intValue];
        NSString *message = response[@"msg"];
        if(code==0){
            NSLog(@"%@",response);
            NSArray *dataAry = [response[@"data"] mj_JSONObject];
            self.dataArray = [NameAndTrueNameModel mj_objectArrayWithKeyValuesArray:dataAry];
//            [UIView performWithoutAnimation:^{
                [self.collectionView reloadSections:[NSIndexSet indexSetWithIndex:2]];
//            }];
        }else{
            SHOWERROR(message)
        }
    } fail:^(NSError *error) {
        SHOWERROR(showNetworkError)
    }];
}


-(float)forWidthFromFont:(UIFont*)font  withHeight:(float)height withString:(NSString*)str
{
    NSMutableParagraphStyle *style = [[NSParagraphStyle defaultParagraphStyle] mutableCopy];
    style.lineBreakMode = NSLineBreakByWordWrapping;
    style.alignment = NSTextAlignmentLeft;
    CGSize size = [str boundingRectWithSize:CGSizeMake(CGFLOAT_MAX, height) options: NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:font, NSParagraphStyleAttributeName:style} context:nil].size;
    
    
    return size.width+1;
}
@end
